/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package components;

import dao.OwnerDAO;
import dao.PetDAO;
import entity.MedicalRecord;
import entity.Owner;
import entity.Pet;
import hpvas.HPVAS;
import java.io.File;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import javax.persistence.EntityExistsException;
import javax.persistence.Persistence;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

/**
 *
 * @author Juan
 */
public class PPetRegistration extends javax.swing.JPanel {

    /**
     * Creates new form PPetRegistration
     */
    public PPetRegistration() {
        initComponents();
        
        FCImageChooser.setFileFilter(new FileFilter() {

            @Override
            public boolean accept(File f) {
                if (!f.isDirectory()) {
                    int i = f.getName().lastIndexOf(".");
                    String extension = f.getName().substring(i + 1).toLowerCase();
                    return extension.equals("jpg") || extension.equals("png") || extension.equals("gif");
                } else {
                    return true;
                }
            }

            @Override
            public String getDescription() {
                return "Pictures (*.jpg, *.png, *.gif)";
            }
        });
        
        OwnerDAO ownerDAO = new OwnerDAO(Persistence.createEntityManagerFactory("HPVA"));
        List<Owner> owners = ownerDAO.findEntities();
        //Ordering the entries:
        TreeSet<Owner> orderedOwners = new TreeSet<>(new Comparator() {

            @Override
            public int compare(Object o1, Object o2) {
                return o1.toString().compareToIgnoreCase(o2.toString());
            }
        });
        orderedOwners.addAll(owners);
        
        DefaultComboBoxModel<Object> model = new DefaultComboBoxModel<>(new Object[] {"<Select an owner>"});
        for (Owner owner : orderedOwners) {
            model.addElement(owner);
        }
        CBOwners.setModel(model);
        
        ComponentFactory.attachVerifier("Please provide the pet's name.", TFName);
        ComponentFactory.attachVerifier("Please provide the pet's species.", TFSpecies);
        ComponentFactory.attachVerifier("Please select the pet's owner.", CBOwners);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        FCImageChooser = new javax.swing.JFileChooser();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        TFName = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        TFSpecies = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        SAge = new javax.swing.JSpinner();
        jLabel5 = new javax.swing.JLabel();
        SWeight = new javax.swing.JSpinner();
        jLabel6 = new javax.swing.JLabel();
        TFPicturePath = new javax.swing.JTextField();
        BBrowse = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        CBOwners = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();
        BRegisterPet = new javax.swing.JButton();
        BCancel = new javax.swing.JButton();

        FCImageChooser.setAcceptAllFileFilterUsed(false);
        FCImageChooser.setCurrentDirectory(new File(".\\pictures"));

        jLabel1.setText("Register Pet:");

        jLabel2.setText("Name:");

        jLabel3.setText("Species:");

        jLabel4.setText("Age:");

        SAge.setModel(new javax.swing.SpinnerNumberModel(0, 0, 1000, 1));

        jLabel5.setText("Weight:");

        SWeight.setModel(new javax.swing.SpinnerNumberModel(Float.valueOf(0.0f), Float.valueOf(0.0f), Float.valueOf(2000.0f), Float.valueOf(1.0f)));

        jLabel6.setText("Picture:");

        TFPicturePath.setEditable(false);

        BBrowse.setText("Browse");
        BBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BBrowseActionPerformed(evt);
            }
        });

        jLabel7.setText("Owner:");

        CBOwners.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<Select an owner>" }));

        jLabel8.setText("Kg");

        BRegisterPet.setText("Register Pet");
        BRegisterPet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BRegisterPetActionPerformed(evt);
            }
        });

        BCancel.setText("Cancel");
        BCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(CBOwners, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(TFName)
                    .addComponent(TFSpecies)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(TFPicturePath)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(BBrowse))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel6)
                            .addComponent(jLabel7)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel4))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(SWeight)
                                    .addComponent(SAge, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel8))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(BRegisterPet)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(BCancel)))
                        .addGap(0, 214, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(TFName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(TFSpecies, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(SAge, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(SWeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(TFPicturePath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(BBrowse))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(CBOwners, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BRegisterPet)
                    .addComponent(BCancel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void BBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BBrowseActionPerformed
        int retVal = FCImageChooser.showDialog(this.getTopLevelAncestor(), "Use Picture");
        
        if (retVal == JFileChooser.APPROVE_OPTION) {
            File selectedFile = FCImageChooser.getSelectedFile();
            TFPicturePath.setText(selectedFile.getAbsolutePath());
        }
    }//GEN-LAST:event_BBrowseActionPerformed

    private void BCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BCancelActionPerformed
        HPVAS.closeCurrentTab();
    }//GEN-LAST:event_BCancelActionPerformed

    private void BRegisterPetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BRegisterPetActionPerformed
        Pet newPet = new Pet();
        CustomVerifier currentVerifier;
        
        currentVerifier = (CustomVerifier) TFName.getInputVerifier();
        if (currentVerifier.isValid()) {
            newPet.setName(TFName.getText().trim());
        } else {
            return;
        }
        
        currentVerifier = (CustomVerifier) TFSpecies.getInputVerifier();
        if (currentVerifier.isValid()) {
            newPet.setSpecies(TFSpecies.getText().trim());
        } else {
            return;
        }
        
        newPet.setAge((int) SAge.getValue());
        newPet.setWeight((float) SWeight.getValue());
        
        if (FCImageChooser.getSelectedFile() != null) {
            newPet.setPicturePath(FCImageChooser.getSelectedFile().getPath());
        } else {
            JOptionPane.showMessageDialog(this.getTopLevelAncestor(),
                    "Please select the picture for this pet.", "Warning", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        currentVerifier = (CustomVerifier) CBOwners.getInputVerifier();
        if (currentVerifier.isValid()) {
            newPet.setOwner((Owner) CBOwners.getSelectedItem());
        } else {
            return;
        }
        
        newPet.setMedicalRecord(new MedicalRecord(newPet));
        
        try {
            PetDAO petDAO = new PetDAO(Persistence.createEntityManagerFactory("HPVA"));
            petDAO.create(newPet);
            
            JOptionPane.showMessageDialog(this.getTopLevelAncestor(),
                    "The pet was registered succesfully.", "Warning", JOptionPane.INFORMATION_MESSAGE);
            
            HPVAS.loadOwners();
            HPVAS.loadPets();
            HPVAS.closeCurrentTab();
        } catch (EntityExistsException e) {
            JOptionPane.showMessageDialog(this.getTopLevelAncestor(),
                    "This pet already exists in the database.", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_BRegisterPetActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BBrowse;
    private javax.swing.JButton BCancel;
    private javax.swing.JButton BRegisterPet;
    private javax.swing.JComboBox CBOwners;
    private javax.swing.JFileChooser FCImageChooser;
    private javax.swing.JSpinner SAge;
    private javax.swing.JSpinner SWeight;
    private javax.swing.JTextField TFName;
    private javax.swing.JTextField TFPicturePath;
    private javax.swing.JTextField TFSpecies;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    // End of variables declaration//GEN-END:variables
}
